package com.pioneer.swing.controller;

import com.pioneer.beans.*;
import com.pioneer.swing.ui.*;
import com.pioneer.swing.model.*;
import com.pioneer.dao.*;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.table.TableModel;
import java.util.Vector;

/**
 * Title:        Pioneer Metals
 * Description:
 * Copyright:    Copyright (c) 2001
 * Company:      Pioneer Metals
 * @author Gary Chen
 * @version 1.0
 */

public class Saver implements ActionListener {


  private ManifestDAO manifestDAO;
	private JobDAO jobDAO;
	private ContactDAO contactDAO;

  private JInternalFrame frame;

  public Saver(JInternalFrame frame) {
	this.frame=frame;
  }
	
	public void setManifestDAO(ManifestDAO manifestDAO) {
		this.manifestDAO=manifestDAO;
	}
	
	public void setContactDAO(ContactDAO contactDAO) {
		this.contactDAO = contactDAO;
	}
	
	public void setJobDAO(JobDAO jobDAO) {
		this.jobDAO = jobDAO;
	}

  public static void main(String[] args) {
    //Saver windowOpener1 = new Saver();
  }

  public void actionPerformed(ActionEvent e) {
    String actionCommand=e.getActionCommand();
    Object queryObj=e.getSource();
    if (actionCommand.equals(UIConstants.COMMAND_SAVE_MANIFEST_BUTTON))
    {
		createManifest();
	} else if (actionCommand.equals(UIConstants.COMMAND_SAVE_JOB_BUTTON)) {
		saveJob();
    }
  }
	
	/**
	* This code gets invoked by the window closing event so edits and news apply
	*/

  public static void saveContainerEntry(ManifestDAO manifestDAO, ContainerEntryFrame containerEntryFrame) {
	String jobNum=containerEntryFrame.jobNumLabel.getText();
	String containerId=containerEntryFrame.containerIdTextField.getText();
	TableModel model=containerEntryFrame.containerContentTable.getModel();
	int maxRows=model.getRowCount();
	
	if (containerEntryFrame.containerIdTextField.isEditable()) {
		try {
			manifestDAO.addContainer(jobNum, 
				new Container(containerEntryFrame.containerIdTextField.getText(),
				containerEntryFrame.supplierNameComboBox.getSelectedItem().toString()));			
		} catch (DataAccessException ex) {
			System.err.println("Couldn't add a new container because "+ex.getMessage());
		}
	}
	else {
		try {
			manifestDAO.updateContainer(jobNum, 
				new Container(containerEntryFrame.containerIdTextField.getText(),
				containerEntryFrame.supplierNameComboBox.getSelectedItem().toString()));
		} catch (DataAccessException ex) {
			System.err.println("Couldn't update container because "+ex.getMessage());
		}
	}
	try {
		manifestDAO.deleteContainerContents(jobNum,containerId);
	} catch (DataAccessException ex) {
		System.err.println("Couldn't remove the old container contents because "+ex.getMessage());
	}
	for (int count=0;count<maxRows;count++) {
		// check key to see if blank
		String desc=model.getValueAt(count,0).toString();
		if (desc.trim().length()>0) {
			//System.out.println("Saving for row "+count);
			//new ContainerContent(desc,weight,fob,fobcnum,fobamt,remarks);
			/*
			columnIdentifiers=new Vector();
			columnIdentifiers.add(TableConstants.DESCRIPTION);
			columnIdentifiers.add(TableConstants.REMARKS);
			columnIdentifiers.add(TableConstants.FOB);
			columnIdentifiers.add(TableConstants.FOB_C_NUM);
			columnIdentifiers.add(TableConstants.WEIGHT);
			columnIdentifiers.add(TableConstants.FOB_AMOUNT);
			*/
			
			ContainerContent content=new ContainerContent(
			desc,
			new Float(model.getValueAt(count,ContainerEntryTable.WEIGHT).toString()).floatValue(),
			"FOB",
			new Float(model.getValueAt(count,ContainerEntryTable.FOB_C_NUM).toString()).floatValue(),
			new Float(model.getValueAt(count,ContainerEntryTable.FOB_AMOUNT).toString()).floatValue(),
			new Float(model.getValueAt(count,ContainerEntryTable.COST).toString()).floatValue(),
			model.getValueAt(count,ContainerEntryTable.PACKING).toString()
			);
			try {
				manifestDAO.addContainerContent(jobNum,
				containerId,
				content);
			}
			catch (DataAccessException ex) {
				System.err.println("Couldn't save the record because "+ex.getMessage());
			}
		}
		else {
			//System.out.println("Skipping row because blank");
		}
	}
  }
	
  //public void saveItemEntry(ManifestDAO manifestDAO, ContainerEntryFrame containerEntryFrame) {
	public void saveItemEntry() {
		JobEntryFrame jobEntryFrame = (JobEntryFrame)this.frame;
		String quoteNum=jobEntryFrame.quoteNumTextField.getText();
		TableModel model=jobEntryFrame.itemsTable.getModel();
		int maxRows=model.getRowCount();
		try {
			jobDAO.deleteJobItems(quoteNum);
		} catch (DataAccessException ex) {
			System.err.println("Couldn't remove the old item contents because "+ex.getMessage());
		}
		for (int count=0;count<maxRows;count++) {
			// check key to see if blank
			String desc=model.getValueAt(count,0).toString();
			if (desc.trim().length()>0) {
				//System.out.println("Saving for row "+count);
				//new ContainerContent(desc,weight,fob,fobcnum,fobamt,remarks);
				/*
				columnIdentifiers=new Vector();
				columnIdentifiers.add(TableConstants.DESCRIPTION);
				columnIdentifiers.add(TableConstants.REMARKS);
				columnIdentifiers.add(TableConstants.FOB);
				columnIdentifiers.add(TableConstants.FOB_C_NUM);
				columnIdentifiers.add(TableConstants.WEIGHT);
				columnIdentifiers.add(TableConstants.FOB_AMOUNT);
				*/
				JobItem jobItem = new JobItem(quoteNum,model.getValueAt(count,ItemEntryTable.ITEM_NUM).toString(),
					model.getValueAt(count,ItemEntryTable.ITEM_DESC).toString(),
					model.getValueAt(count,ItemEntryTable.ITEM_QTY).toString(),					
					model.getValueAt(count,ItemEntryTable.ITEM_PRICE).toString());
				
				try {
					jobDAO.addJobItem(jobItem);
				}
				catch (DataAccessException ex) {
					System.err.println("Couldn't save the record because "+ex.getMessage());
				}
			}
			else {
				//System.out.println("Skipping row because blank");
			}
		}
	  }	
	
	/**
	* This code gets invoked by the window closing event so edits and news apply
	*/
	
	//public static void saveJob(JobDAO jobDAO, JobEntryFrame jobFrame) {
	public void saveJob() {
		JobEntryFrame jobFrame = (JobEntryFrame)this.frame;
		Job job = null;
		try {
			job = new Job(jobFrame.quoteNumTextField.getText(),	jobFrame.jobDateTextField.getText(),	
			jobFrame.jobNameTextField.getText(),
			jobFrame.addressTextField.getText(),
			jobFrame.cityTextField.getText(),
			jobFrame.stateTextField.getText(),
			jobFrame.zipTextField.getText(),
			jobFrame.salesRepComboBox.getSelectedItem().toString(),
			jobFrame.regSalesManComboBox.getSelectedItem().toString(),
			jobFrame.numOfUnitsTextField.getText(),
			jobFrame.typeComboBox.getSelectedItem().toString(),
			jobFrame.supplierNameComboBox.getSelectedItem().toString(),
			jobFrame.supplierContactTextField.getText(),	
			jobFrame.contractorNameComboBox.getSelectedItem().toString(),
			jobFrame.contractorContactTextField.getText(),
			jobFrame.builderNameComboBox.getSelectedItem().toString(),
			jobFrame.statusComboBox.getSelectedItem().toString(),
			jobFrame.shipDateTextField.getText(),
			jobFrame.termsTextField.getText(),jobFrame.notesTextField.getText(),
			jobFrame.expirationDateTextField.getText());
			//System.out.println("Notes are "+jobFrame.notesTextField.getText());
		}
		catch (java.text.ParseException ex) {
			System.err.println("Couldn't parse the date string");
		}
		
		boolean isNew=jobFrame.quoteNumTextField.isEditable();
		if (isNew) {
			try {
				//System.out.println("just created manifest "+jobNum);
	    		jobDAO.addJob(job);
				//((AllContainersTable)manifestEntryFrame.containerListTable.getModel()).updateJobNum(jobNum);
				} catch (DataAccessException ex) {
					System.err.println("Couldn't add a new job because "+ex.getMessage());
				}
		}
		else {
			try {
				String quoteNum=jobFrame.quoteNumTextField.getText();
				jobDAO.updateJob(job);
			} catch (DataAccessException ex) {
				System.err.println("Couldn't update the job because "+ex.getMessage());
			}
		}
		saveItemEntry();
	 //System.out.println("Saving job");	
  	}
	
	/**
	* This code gets invoked by the window closing event so edits and news apply
	*/

  public static void saveManifest(ManifestDAO manifestDAO, ManifestEntryFrame manifestEntryFrame) {
	Manifest manifest=null;
	try {
		manifest=new Manifest(manifestEntryFrame.jobTextField.getText(),
			manifestEntryFrame.getManifestType(),
			manifestEntryFrame.vesselTextField.getText(),
			manifestEntryFrame.etdTextField.getText(),
			manifestEntryFrame.etaTextField.getText(),
			manifestEntryFrame.notesTextField.getText(),
			manifestEntryFrame.freightTextField.getText(),
			manifestEntryFrame.truckingTextField.getText(),
			manifestEntryFrame.miscTextField.getText());
	}
	catch (java.text.ParseException ex) {
		System.err.println("Couldn't parse the date string");
	}
	boolean isNew=manifestEntryFrame.jobTextField.isEditable();
	if (isNew) {
		try {
			//System.out.println("just created manifest "+jobNum);
    		manifestDAO.addManifest(manifest);
			//((AllContainersTable)manifestEntryFrame.containerListTable.getModel()).updateJobNum(jobNum);
			} catch (DataAccessException ex) {
			System.err.println("Couldn't add a new manifest because "+ex.getMessage());
		}
	}
	else {
		try {
			String jobNum=manifestEntryFrame.jobTextField.getText();
			manifestDAO.updateManifest(jobNum,manifest);
		} catch (DataAccessException ex) {
			System.err.println("Couldn't update the manifest because "+ex.getMessage());
		}
	}
  }
	
	/**
	* This code only applies to the create manifest button because we need to save a manifest before entering container information
	*/

  private void createManifest() {
	ManifestEntryFrame manifestEntryFrame=(ManifestEntryFrame)frame;
	ErrorCode errCode=Validator.validate(manifestEntryFrame, manifestDAO);
	if (errCode.getErrCode()!=ErrorCode.OK) {
		JOptionPane.showMessageDialog(manifestEntryFrame, errCode.getErrMesg(),
		UIConstants.TITLE_SAVE_CONFIRM, JOptionPane.INFORMATION_MESSAGE);
		manifestEntryFrame.jobTextField.setText("");
	}
	else {
		boolean isNew=manifestEntryFrame.jobTextField.isEditable();
		if (isNew) {
			try {
				Manifest manifest=new Manifest(manifestEntryFrame.jobTextField.getText(),
				manifestEntryFrame.getManifestType(),
					manifestEntryFrame.vesselTextField.getText(),
				manifestEntryFrame.etdTextField.getText(),
				manifestEntryFrame.etaTextField.getText(),
				manifestEntryFrame.notesTextField.getText(),
				manifestEntryFrame.freightTextField.getText(),
				manifestEntryFrame.truckingTextField.getText(),
				manifestEntryFrame.miscTextField.getText());
				manifestDAO.addManifest(manifest);
				manifestEntryFrame.jobTextField.setEditable(false);
				manifestEntryFrame.createManifestButton.setEnabled(false);
				manifestEntryFrame.newButton.setEnabled(true);
				manifestEntryFrame.editButton.setEnabled(true);
				manifestEntryFrame.deleteButton.setEnabled(true);

			} catch (DataAccessException ex) {
				System.err.println("Couldn't add a new manifest because "+ex.getMessage());
			} catch (java.text.ParseException ex) {
				System.err.println("Couldn't parse the date string");
			}
		}
	}
  }


}